<?php
/** 过滤器接口 */
interface Filter {
    public function execute($request);
}
class AuthenticationFilter implements Filter
{
    public function execute($request)
    {
        echo "Authenticating request: $request\r\n";
    }
}
class DebugFilter implements Filter
{
    public function execute($request)
    {
        echo "request log: $request\r\n";
    }
}
/** 要执行的目标程序 */
class Target
{
    public function execute($request)
    {
        echo "Executing request: $request\r\n";
    }
}
/** 过滤器链 */
class FilterChain
{
    /** @var Filter[] $filters */
    protected $filters = [];
    /** @var Target $target */
    protected $target = null;
    public function addFilter($filter)
    {
        $this->filters[] = $filter;
    }
    public function setTarget($target){
        $this->target = $target;
    }
    public function execute($request)
    {
        foreach($this->filters as $filter){
            $filter->execute($request);
        }
        $this->target->execute($request);
    }
}
class FilterManager
{
    /** @var FilterChain $chain */
    protected $chain;
    public function __construct($target)
    {
        $this->chain = new FilterChain;
        $this->chain->setTarget($target);
    }
    public function setFilter($filter)
    {
        $this->chain->addFilter($filter);
    }
  
    public function filterRequest($request)
    {
        $this->chain->execute($request);
    }
}
class Client
{
    /** @var FilterManager $filterManager */
    protected $filterManager;
    public function setFilterManager($filterManager)
    {
        $this->filterManager = $filterManager;
    }
    public function sendRequest($request)
    {
        $this->filterManager->filterRequest($request);
    }
}

header('Content-Type: text/plain');

$manager = new FilterManager(new Target);
$manager->setFilter(new AuthenticationFilter);
$manager->setFilter(new DebugFilter);

$client = new Client;
$client->setFilterManager($manager);
$client->sendRequest("home");
